import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch } from '../hooks/useAppDispatch';
import { useAppSelector } from '../hooks/useAppSelector';
import { setUser, setToken, selectIsAuthenticated, selectUser } from '../store/authSlice';
import axiosInstance from '../api/axios';
import { login } from '../api/userApi';
import { Loader2, User, Lock } from 'lucide-react';

const Login = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const isAuthenticated = useAppSelector(selectIsAuthenticated);
  const user = useAppSelector(selectUser);

  useEffect(() => {
    if (isAuthenticated && user) {
      if (user.role === 1) {
        navigate('/admin');
      } else {
        navigate('/dashboard');
      }
    }
  }, [isAuthenticated, user, navigate]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setIsLoading(true);

    try {
      const formData = new URLSearchParams();
      formData.append('username', username);
      formData.append('password', password);

      const response = await login(formData);

      if (!response.data.access_token) {
        throw new Error('No access token received');
      }

      const token = response.data.access_token;
      dispatch(setToken(token));
      axiosInstance.defaults.headers.common['Authorization'] = `Bearer ${token}`;

      try {
        const userResponse = await axiosInstance.get('/users/me');
        dispatch(setUser(userResponse.data));

        if (userResponse.data.role === 1) {
          navigate('/admin');
        } else {
          navigate('/dashboard');
        }
      } catch {
        setError('获取用户信息失败，请重试。');
        dispatch(setToken(''));
      }
    } catch (err: any) {
      setError(err.response?.data?.detail || '登录失败，请检查用户名或密码。');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-100 to-gray-200 px-4">
      <div className="w-full max-w-md">
        <div className="bg-white shadow-lg rounded-xl p-8 space-y-6 border border-gray-200">
          <h2 className="text-center text-2xl font-bold text-gray-800">
            配置管理系统
          </h2>
          <p className="text-center text-gray-500 text-sm">请登录以继续</p>

          <form className="space-y-5" onSubmit={handleSubmit}>
            <div className="relative">
              <User className="absolute left-3 top-2.5 text-gray-400 w-5 h-5" />
              <input
                id="username"
                name="username"
                type="text"
                required
                disabled={isLoading}
                className="w-full pl-10 pr-3 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-blue-400"
                placeholder="用户名"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
              />
            </div>

            <div className="relative">
              <Lock className="absolute left-3 top-2.5 text-gray-400 w-5 h-5" />
              <input
                id="password"
                name="password"
                type="password"
                required
                disabled={isLoading}
                className="w-full pl-10 pr-3 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-blue-400"
                placeholder="密码"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
            </div>

            {error && (
              <div className="text-red-500 text-sm text-center animate-fade-in">
                {error}
              </div>
            )}

            <button
              type="submit"
              disabled={isLoading}
              className="w-full flex justify-center items-center gap-2 py-2 px-4 rounded-lg text-white font-medium bg-gradient-to-r from-blue-600 to-blue-500 hover:from-blue-700 hover:to-blue-600 transition disabled:opacity-50"
            >
              {isLoading ? (
                <>
                  <Loader2 className="animate-spin w-4 h-4" /> 登录中...
                </>
              ) : (
                '登录'
              )}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
};

export default Login;
